package com.yunc.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.common.schedule.SchedulerUtils;
import com.yunc.modules.sys.entity.SysJob;
import com.yunc.modules.sys.mapper.SysJobMapper;
import com.yunc.modules.sys.service.ISysJobService;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 定时任务
 * @author congcong tao
 * @create 2018/11/3 下午9:41
 */
@Service("sysJobService")
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper,SysJob> implements ISysJobService {

    @Autowired
    private SysJobMapper sysJobMapper;
    @Autowired
    private Scheduler scheduler;

    @PostConstruct
    public void initScheduleJob() {
        SysJob recordJob = new SysJob();
        // recordJob.setStatus("0");
        List<SysJob> jobs = this.list(new QueryWrapper<>(recordJob));
        if (jobs == null || jobs.size() == 0) {
            return;
        }
        for (SysJob record : jobs) {
            String name = record.getJobName();
            String group = record.getJobGroup();
            CronTrigger cronTrigger = SchedulerUtils.getCronTrigger(scheduler, name, group);
            if (cronTrigger == null) {
                SchedulerUtils.createScheduleJob(record, scheduler);
            } else {
                SchedulerUtils.updateScheduleJob(scheduler, record);
            }
        }
    }
}
